<template>
  <!-- 成行路线 -->
  <div class="app-container2">

    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="路线" prop="route">
        <el-input v-model="queryParams.route" placeholder="请输入路线名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="路线状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请输入路线名" clearable @keyup.enter.native="handleQuery">
          <el-option label="可报名" value="0"></el-option>
          <el-option label="已开启补报" value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <!-- 排序 -->
        <el-button type="primary" @click="handleSortByDate" size="mini" plain>按开始日期排序</el-button>
        <el-button type="success" @click="handleSortByCount" size="mini" plain>按已选人数排序</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="6">
        <el-button type="success" size="medium" :disabled="multiple" @click="setNotCango"
          v-hasPermi="['lxy:time:edit']">取消成行
        </el-button>
      </el-col>
      <!-- 补报设置 -->
      <el-col :span="3.5">
        <el-date-picker v-model="value1" type="datetimerange" range-separator="至" start-placeholder="开始日期"
          end-placeholder="结束日期" value-format="yyyy-MM-dd HH:mm:ss" @change="checkDate">
        </el-date-picker>
      </el-col>
      <el-col :span="1">
        <el-button type="success" size="medium" :disabled="isDateEmpty || multiple" @click="handleStartReselect"
          v-hasPermi="['lxy:time:edit']">开启补报
        </el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <!-- 数据显示表单 -->
    <el-table v-loading="loading" :data="timeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="时间段编号" align="center" prop="id" />
      <el-table-column label="路线" align="center" prop="route" />
      <el-table-column label="开始日期" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束日期" align="center" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="人数上限" align="center" prop="max" />
      <el-table-column label="职工上限" align="center" prop="staffMax" />
      <el-table-column label="已选人数" align="center" prop="count" />
      <el-table-column label="已选职工人数" align="center" prop="staffCount" />
      <el-table-column label="路线状态" align="center" prop="status" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['lxy:time:edit']">修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-list" @click="handleViewList(scope.row)"
            v-hasPermi="['lxy:time:remove']">查看名单
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改时间段对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="路线id" prop="routeId">
          <el-input v-model="form.routeId" placeholder="请输入路线id" />
        </el-form-item>
        <el-form-item label="开始日期" prop="startTime">
          <el-date-picker clearable v-model="form.startTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择开始日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期" prop="endTime">
          <el-date-picker clearable v-model="form.endTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="人数上限" prop="max">
          <el-input v-model="form.max" placeholder="请输入人数上限" />
        </el-form-item>
        <el-form-item label="已选人数" prop="count">
          <el-input v-model="form.count" placeholder="请输入已选人数" />
        </el-form-item>
        <el-form-item label="职工上限" prop="staffMax">
          <el-input v-model="form.staffMax" placeholder="请输入职工上限" />
        </el-form-item>
        <el-form-item label="已选职工人数" prop="staffCount">
          <el-input v-model="form.staffCount" placeholder="请输入已选职工人数" />
        </el-form-item>
        <!-- <el-form-item label="是否成团" prop="canGo">
          <el-input v-model="form.canGo" placeholder="请选择是否成团" />
        </el-form-item> -->
        <el-form-item label="是否成团">
          <el-select v-model="queryParams.canGo" placeholder="请选择是否成团">
            <el-option label="成团" value="1"></el-option>
            <el-option label="不成团" value="0"></el-option>
          </el-select>
        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getTime, setNotCanGo, addTime, updateTime, listCanGoTime, startReselect } from "@/api/lxy/time";

export default {
  name: "Time",
  data() {
    return {
      value1: [],
      // 补报
      reselectStart: undefined,
      reselectEnd: undefined,
      /* 排序 */
      sortType: 'asc', // 默认升序排序
      sortBy: 'count', // 默认按人数排序
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 时间段表格数据
      timeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        routeId: undefined,
        startTime: undefined,
        endTime: undefined,
        max: undefined,
        count: undefined,
        staffMax: undefined,
        staffCount: undefined,
        canGo: "",
        status: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        id: [
          { required: true, message: "时间段表不能为空", trigger: "blur" }
        ],
        routeId: [
          { required: true, message: "路线id不能为空", trigger: "blur" }
        ],
        startTime: [
          { required: true, message: "开始日期不能为空", trigger: "blur" }
        ],
        endTime: [
          { required: true, message: "结束日期不能为空", trigger: "blur" }
        ],
        max: [
          { required: true, message: "人数上限不能为空", trigger: "blur" }
        ],
        count: [
          { required: true, message: "已选人数不能为空", trigger: "blur" }
        ],
        staffMax: [
          { required: true, message: "职工上限不能为空", trigger: "blur" }
        ],
        staffCount: [
          { required: true, message: "已选职工人数不能为空", trigger: "blur" }
        ],
        canGo: [
          { required: true, message: "是否成团不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ],
      }
    };
  },

  props: {
    // 父组件传递的项目id、项目名
    pId: Number,
  },

  computed: {
    isDateEmpty() {
      return !this.reselectStart || !this.reselectEnd;
    }
  },

  created() {
    this.getList();
  },
  methods: {
    checkDate() {
      if (this.value1 && this.value1.length === 2) {
        this.reselectStart = this.formatDate(this.value1[0]);
        this.reselectEnd = this.formatDate(this.value1[1]);
      }
    },
    formatDate(date) {
      const formattedDate = new Date(date).toISOString().slice(0, 19).replace('T', ' ');
      return formattedDate;
    },
    /** 开启补报 */
    handleStartReselect(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认将路线' + ids + '开启补报').then(() => {
        this.loading = true;
        return startReselect(this.reselectStart, this.reselectEnd, ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess('开启补报成功');
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },

    /** 点击按已选人数排序按钮 */
    handleSortByCount() {
      this.sortBy = 'count';
      this.handleSort();
    },

    /** 点击按开始日期排序按钮 */
    handleSortByDate() {
      this.sortBy = 'date';
      this.handleSort();
    },

    /** 排序 */
    handleSort() {
      if (this.sortType === 'asc') {
        this.sortType = 'desc'; // 切换为降序排序
      } else {
        this.sortType = 'asc'; // 切换为升序排序
      }
      this.getList(); // 获取数据并进行排序
    },
    /** 查询时间段列表 */
    getList() {
      // 项目id
      const projectId = this.pId;
      this.loading = true;
      listCanGoTime(projectId, this.queryParams).then(response => {
        this.timeList = response.rows;
        // 根据排序方式和排序字段对时间段列表进行排序
        if (this.sortBy === 'count') {
          // 按人数排序
          if (this.sortType === 'asc') {
            this.timeList.sort((a, b) => a.count - b.count); // 按人数升序排序
          } else {
            this.timeList.sort((a, b) => b.count - a.count); // 按人数降序排序
          }
        } else if (this.sortBy === 'date') {
          // 按开始日期排序
          if (this.sortType === 'asc') {
            this.timeList.sort((a, b) => new Date(a.startTime) - new Date(b.startTime)); // 按开始日期升序排序
          } else {
            this.timeList.sort((a, b) => new Date(b.startTime) - new Date(a.startTime)); // 按开始日期降序排序
          }
        }
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        routeId: undefined,
        startTime: undefined,
        endTime: undefined,
        remark: undefined,
        max: undefined,
        count: undefined,
        staffMax: undefined,
        staffCount: undefined,
        canGo: undefined,
        status: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getTime(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改时间段";
      });
    },
    /** 设置成行按钮操作 */
    setNotCango(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认将路线' + ids + '取消成行').then(() => {
        this.loading = true;
        return setNotCanGo(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess('取消成行成功');
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateTime(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addTime(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },




    /** 查看名单 */
    handleViewList(row) {
      const id = row.id;
      this.$router.push({
        path: '/lxy/time_cango/viewList/show/' + id,
        query: {
          timeId: id
        }
      })
    },
  }
};
</script>
